import { LOGINUSERID, DOWNLOADFILE,SAVELOCALFILE, SCREENSHOTWINDOWS,SCREENCAPTURE,RENDERPROCESSCALL, SHOWDIALOG, CHECK_FILE_EXIST, SELECT_FILES, GET_VIDEO_INFO, SET_VIDEO_INFO } from "../../app/const/const";

import  { ipcRenderer } from 'electron';
import { getCurrentWindow } from '@electron/remote';
import fs from 'fs';
import path from 'path';
import os from 'os'
import { getFileTypeName } from "./message-input-util";

const WIN = getCurrentWindow();
const SUPPORT_IMAGE_TYPE = ['png', 'jpg', 'gif','jpeg','webp'];
const SUPPORT_VIDEO_TYPE = ['mp4', 'mov'];
const isWin = () => {
    const platform = process.platform;
    return platform === 'win32' || platform === 'linux';
}
const minSizeWin = () => {
    WIN.minimize();
}
const maxSizeWin = () => {
    if(WIN.isMaximized()){
        WIN.unmaximize()
    } else {
        WIN.maximize()
    }
}
const closeWin = () => {
    WIN.close()
}

const showDialog = ()=>{
    ipcRenderer.send(RENDERPROCESSCALL,{
        type:SHOWDIALOG
    })
}
const setLoginIMtoprocess= (userid)=>{
    ipcRenderer.send(RENDERPROCESSCALL,{
        type:LOGINUSERID,
        params:userid
    })
}
const savetoLocal = (file_url:string)=>{
    ipcRenderer.send(RENDERPROCESSCALL,{
        type:SAVELOCALFILE,
        params: file_url
    })
}
const downloadFilesByUrl = (file_url:string,isDecry:boolean=false)=>{
    ipcRenderer.send(RENDERPROCESSCALL,{
        type:DOWNLOADFILE,
        params:{ file_url,isDecry}
    })
}
const checkFileExist = (path) =>{
    ipcRenderer.send(RENDERPROCESSCALL,{
        type:CHECK_FILE_EXIST,
        params:path
    })
}
const selectFileMessage = () => {
    ipcRenderer.send(RENDERPROCESSCALL,{
        type: SELECT_FILES,
        params: {
            fileType: "file",
            extensions: ["*"],
            multiSelections: false
        }
    })
}
const selectVideoMessage = () => {
    ipcRenderer.send(RENDERPROCESSCALL,{
        type: SELECT_FILES,
        params: {
            fileType: "video",
            extensions: SUPPORT_VIDEO_TYPE,
            multiSelections: false
        }
    })
}
const selectImageMessage = () => {
    ipcRenderer.send(RENDERPROCESSCALL,{
        type: SELECT_FILES,
        params: {
            fileType: "image",
            extensions: SUPPORT_IMAGE_TYPE,
            multiSelections: false
        }
    })
}

const readScreenShot = () => {
    ipcRenderer.send(RENDERPROCESSCALL,{
        type: SCREENCAPTURE,
    })
}

const readScreenShotWindows = () => {
    ipcRenderer.send(RENDERPROCESSCALL,{
        type: SCREENSHOTWINDOWS,
    })
}
const setVideoInfo = (path,isVideo)=>{
    return new Promise((resolve, reject) => {
        ipcRenderer.send(RENDERPROCESSCALL, {
            type: SET_VIDEO_INFO,params: { path: path,isVideo}
        });
        ipcRenderer.once("SET_VIDEO_INFO_CALLBACK", (event, data) => {
            resolve(data);
        });
    });
}

const getVideoInfo = (path)=>{
    return new Promise((resolve, reject) => {
        ipcRenderer.send(RENDERPROCESSCALL, {
            type: GET_VIDEO_INFO,params: { path: path}
        });
        ipcRenderer.once("GET_VIDEO_INFO_CALLBACK", (event, data) => {
            resolve(data.data);
        });
    });
}
const generateRoomID = () => {
    return Math.floor(Math.random() * 1000);
}
const crypto = require("crypto");
const key = Buffer.from("128bitslength*@#", "utf8");
const iv = Buffer.from("A-16-Byte-String", "utf8");
const aesEncry=(words)=>{
    const cipher = crypto.createCipheriv("AES-128-CBC", key, iv);
    // toHex
    let cText = cipher.update(words, "utf-8", "base64");
    cText += cipher.final("base64");
    return cText;
}
const aesDecry=(words)=>{
    const decipher = crypto.createDecipheriv("AES-128-CBC", key, iv);
    let dText = decipher.update(words, "base64", "utf-8");
    dText += decipher.final("utf8");
    return dText;
}

// 加密文件
function aesFile(url,downpath=null) {
  return new Promise((resolve, reject) => {
    const input = fs.createReadStream(url);
    //const name = getFileName(url);  //总有文件获取不到unknown
    const urlname =Buffer.from(url).toString("base64");
    const filetp ="."+ getFileTypeName(url);
    let newPath =path.resolve(os.homedir(),'download/'+urlname + filetp);
    if(fs.existsSync(newPath)){
        console.log(newPath+"文件存在")
        fs.rmSync(newPath);  //有可能之前的文件已坏，故删除
    } 
    const output = fs.createWriteStream(newPath);
    const cipher = crypto.createCipheriv("AES-128-CBC", key, iv);
    input.pipe(cipher).pipe(output);
    output.on('finish', () => {
        if(downpath){
          // 计算MD5值
          const hash = crypto.createHash('md5');
          const input = fs.createReadStream(newPath);
          input.on('readable', () => {
              const data = input.read();
              if (data) {
                  hash.update(data);
              } else {
                const md5 = hash.digest('hex');
                const newout = path.resolve(downpath,md5+ filetp);
                if(fs.existsSync(newout))
                    fs.rmSync(url);
                else
                  fs.renameSync(url,newout);
                resolve({newPath,newout:md5+filetp});
              }
          });
        }
        else{
            resolve({newPath});
        }
        
      //console.log("AES file "+newPath);
    });
    output.on('error', (err) => {
      reject(err);
    });
  });
}

// const aesFileDecry = (url) => {
//     fs.renameSync(url,url+".down");
//     const input = fs.createReadStream(url+".down");
//     const output = fs.createWriteStream(url);
//     const decipher = crypto.createDecipheriv("AES-128-CBC", key, iv);
//     input.pipe(decipher).pipe(output);
  
//     return new Promise((resolve, reject) => {
//       output.on('finish', () => {
//         fs.rmSync(url+".down")
//         resolve(url);
//       });
//       output.on('error', (err) => {
//         reject(err);
//       });
//     });
// }

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
export {
    isWin,sleep,
    minSizeWin,
    maxSizeWin,
    closeWin,
    showDialog,
    downloadFilesByUrl,savetoLocal,
    checkFileExist,
    generateRoomID,
    selectFileMessage,
    selectVideoMessage,
    selectImageMessage,
    getVideoInfo,setVideoInfo,
    SUPPORT_IMAGE_TYPE,
    SUPPORT_VIDEO_TYPE,
    aesEncry,aesDecry,aesFile,setLoginIMtoprocess,
    readScreenShot,readScreenShotWindows
}
